<template>
  <view class="confirm-order-page">
    <!-- 进度指示器 -->
    <view class="progress-section">
      <view class="progress-bar">
        <view class="progress-step completed">
          <view class="step-circle">1</view>
          <text class="step-text">预约服务</text>
        </view>
        <view class="progress-line"></view>
        <view class="progress-step current">
          <view class="step-circle">2</view>
          <text class="step-text">支付订单</text>
        </view>
        <view class="progress-line"></view>
        <view class="progress-step">
          <view class="step-circle">3</view>
          <text class="step-text">门店服务</text>
        </view>
      </view>
    </view>

    <!-- 门店信息 -->
    <view class="info-section">
      <view class="info-item">
        <image src="@/img/车联网服务-04汽车保养-06确认订单_slices/商家@3x.png" class="info-icon"></image>
        <view class="info-content">
          <text class="info-title">{{orderData.storeInfo.name}}</text>
          <text class="info-desc">{{orderData.storeInfo.address}}</text>
        </view>
      </view>
    </view>

    <!-- 用户信息 -->
    <view class="info-section">
      <view class="info-item">
        <image src="@/img/车联网服务-04汽车保养-06确认订单_slices/人员@3x.png" class="info-icon"></image>
        <view class="info-content">
          <text class="info-title">{{userInfo.name}}</text>
          <text class="info-desc">{{userInfo.phone}}</text>
        </view>
      </view>
    </view>

    <!-- 预约详情 -->
    <view class="info-section">
      <view class="info-item clickable" @click="selectAppointmentTime">
        <image src="@/img/车联网服务-04汽车保养-06确认订单_slices/车辆-01@3x.png" class="info-icon"></image>
        <view class="info-content">
          <text class="info-title">{{appointmentTime || '立即预约'}}</text>
        </view>
        <image src="@/img/车联网服务-04汽车保养-06确认订单_slices/收起箭头小 拷贝@3x.png" class="arrow-icon"></image>
      </view>
      
      <view class="info-item clickable" @click="selectVehicle">
        <image src="@/img/车联网服务-04汽车保养-06确认订单_slices/车辆-01@3x(1).png" class="info-icon"></image>
        <view class="info-content">
          <text class="info-title" v-if="vehicleInfo.id">{{vehicleInfo.type}}/{{vehicleInfo.carNum}}</text>
          <text class="info-title vehicle-placeholder" v-else>请选择车辆</text>
        </view>
        <image src="@/img/车联网服务-04汽车保养-06确认订单_slices/收起箭头小 拷贝@3x.png" class="arrow-icon"></image>
      </view>
    </view>

    <!-- 服务产品 -->
    <view class="services-section">
      <view class="section-header">
        <text class="section-title">服务产品</text>
        <text class="service-count">共选择{{orderData.selectedServices.length}}项服务产品</text>
      </view>
      
      <view class="service-list">
        <view class="service-item" v-for="(service, index) in orderData.selectedServices" :key="index">
          <text class="service-name">{{service.name}}</text>
          <text class="service-price">¥ {{service.currentPrice}}</text>
        </view>
      </view>
    </view>

    <!-- 优惠券 -->
    <view class="info-section">
      <view class="info-item clickable" @click="selectCoupon">
        <image src="@/img/车联网服务-04汽车保养-06确认订单_slices/优惠券@3x.png" class="info-icon"></image>
        <view class="info-content">
          <text class="info-title">代金券/优惠券</text>
          <text class="info-desc">{{selectedCoupon ? formatCouponAmount(selectedCoupon) : '暂无'}}</text>
        </view>
        <image src="@/img/车联网服务-04汽车保养-06确认订单_slices/收起箭头小 拷贝@3x.png" class="arrow-icon"></image>
      </view>
    </view>

    <!-- 备注信息 -->
    <view class="remarks-section">
      <text class="remarks-label">备注信息</text>
      <textarea 
        class="remarks-input" 
        placeholder="请输入备注信息（选填）"
        v-model="remarks"
        maxlength="200"
      ></textarea>
    </view>

    <!-- 预约时间选择弹窗 -->
    <view class="appointment-modal-overlay" v-if="showAppointmentModal" @click="closeAppointmentModal">
      <view class="appointment-modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">预约时间</text>
          <text class="modal-subtitle">({{currentDateTime}})</text>
        </view>
        
        <view class="modal-content">
          <view class="book-now-option" @click="selectBookNow">
            <text class="book-now-text">立即预约</text>
          </view>
          
          <view class="time-selection">
            <view class="date-column">
              <view 
                class="date-item" 
                v-for="(date, index) in availableDates" 
                :key="index"
                :class="{ 'selected': selectedDateIndex === index, 'disabled': date.disabled }"
                @click="selectDate(index)"
              >
                <text class="date-text">{{date.text}}</text>
              </view>
            </view>
            
            <view class="time-column">
              <view 
                class="time-item" 
                v-for="(time, index) in availableTimes" 
                :key="index"
                :class="{ 'selected': selectedTimeIndex === index, 'disabled': time.disabled }"
                @click="selectTime(index)"
              >
                <text class="time-text">{{time.text}}</text>
              </view>
            </view>
          </view>
        </view>
        
        <view class="modal-footer">
          <button class="cancel-btn" @click="closeAppointmentModal">取消</button>
          <button class="confirm-btn" @click="confirmAppointment">确定</button>
        </view>
      </view>
    </view>

    <!-- 车辆选择弹窗 -->
    <view class="vehicle-modal-overlay" v-if="showVehicleModal" @click="closeVehicleModal">
      <view class="vehicle-modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">选择车辆</text>
          <text class="close-btn" @click="closeVehicleModal">×</text>
        </view>
        
        <view class="modal-content">
          <view 
            class="vehicle-item" 
            v-for="(vehicle, index) in vehicleList" 
            :key="index"
            @click="selectSpecificVehicle(vehicle)"
            :class="{ 'selected': vehicleInfo.id === vehicle.id }"
          >
            <view class="vehicle-info">
              <text class="vehicle-type">{{vehicle.type}}</text>
              <text class="vehicle-number">{{vehicle.carNum}}</text>
              <text class="default-tag" v-if="vehicle.isDefault">默认</text>
            </view>
            <view class="vehicle-check" v-if="vehicleInfo.id === vehicle.id">
              <text class="check-icon">✓</text>
            </view>
          </view>
          
          <view v-if="vehicleList.length === 0" class="no-vehicle">
            <text>您还没有添加车辆</text>
          </view>
        </view>
        
        <view class="modal-footer">
          <button class="add-vehicle-btn" @click="addNewVehicle">添加新车辆</button>
        </view>
      </view>
    </view>

    <!-- 优惠券选择弹窗 -->
    <view class="coupon-modal-overlay" v-if="showCouponModal" @click="closeCouponModal">
      <view class="coupon-modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">选择优惠券</text>
          <text class="close-btn" @click="closeCouponModal">×</text>
        </view>
        
        <view class="modal-content">
          <!-- 不使用优惠券选项 -->
          <view 
            class="coupon-item no-coupon-item" 
            @click="selectNoCoupon"
            :class="{ 'selected': !selectedCoupon }"
          >
            <view class="coupon-info">
              <text class="coupon-title">不使用优惠券</text>
            </view>
            <view class="coupon-check" v-if="!selectedCoupon">
              <text class="check-icon">✓</text>
            </view>
          </view>
          
          <!-- 优惠券列表 -->
          <view 
            class="coupon-item" 
            v-for="(coupon, index) in availableCoupons" 
            :key="index"
            @click="selectSpecificCoupon(coupon)"
            :class="{ 
              'selected': selectedCoupon && selectedCoupon.id === coupon.id,
              'disabled': !isCouponUsable(coupon)
            }"
          >
            <view class="coupon-info">
              <text class="coupon-title">{{coupon.coupon.name}}</text>
              <text class="coupon-desc">{{formatCouponAmount(coupon)}}</text>
              <text class="coupon-expire">有效期至：{{coupon.coupon.expirationEnd}}</text>
              <text class="coupon-condition" v-if="!isCouponUsable(coupon)">
                不满足使用条件
              </text>
            </view>
            <view class="coupon-check" v-if="selectedCoupon && selectedCoupon.id === coupon.id">
              <text class="check-icon">✓</text>
            </view>
          </view>
          
          <view v-if="availableCoupons.length === 0" class="no-coupon">
            <text>暂无可用优惠券</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 支付密码弹窗 -->
    <view class="payment-modal-overlay" v-if="showPaymentModal" @click="closePaymentModal">
      <view class="payment-modal" @click.stop>
        <view class="payment-header">
          <text class="close-btn" @click="closePaymentModal">×</text>
          <text class="payment-title">请输入支付密码</text>
        </view>
        
        <view class="payment-amount">
          <text class="amount-symbol">¥</text>
          <text class="amount-number">{{totalPrice}}</text>
        </view>
        
        <view class="payment-method">
          <!-- 支付方式和零钱标签 -->
          <view class="payment-labels">
            <text class="method-label">支付方式</text>
            <text class="balance-text">零钱></text>
          </view>
          
          <!-- 6位密码输入框 -->
          <view class="password-input-container">
            <input 
              type="number" 
              class="hidden-input"
              v-model="paymentPassword"
              maxlength="6"
              @input="onPasswordInput"
              @confirm="verifyPaymentPassword"
              focus
            />
            <view class="password-boxes">
              <view 
                class="password-box"
                v-for="(digit, index) in 6" 
                :key="index"
                :class="{ 'filled': index < paymentPassword.length }"
              >
                <text class="box-text" v-if="index < paymentPassword.length">●</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-bar">
      <view class="left-section">
        <view class="customer-service">
          <image src="@/img/车联网服务-04汽车保养-06确认订单_slices/客服@3x.png" class="service-icon"></image>
          <text class="service-text">联系客服</text>
        </view>
      </view>
      
      <view class="right-section">
        <view class="total-price">
          <text class="total-label">合计:</text>
          <text class="total-value">¥{{totalPrice}}</text>
        </view>
        
        <button class="submit-btn" @click="submitOrder">提交订单</button>
      </view>
    </view>
  </view>
</template>

<script>
import { maintenanceMerchantApi, maintenanceServiceApi, userApi, maintenanceOrderApi, maintenanceCarApi, maintenanceCouponApi } from '@/api/index.js';

export default {
  data() {
    return {
      loading: false,
      loadingUser: false,
      loadingVehicle: false,
      userId: null,
      orderData: {
        storeInfo: {},
        selectedServices: []
      },
      userInfo: {
        id: null,
        name: '',
        phone: ''
      },
      vehicleInfo: {
        id: null,
        type: '请选择车辆',
        carNum: '',
        brand: '',
        model: ''
      },
      vehicleList: [], // 用户车辆列表
      showVehicleModal: false, // 车辆选择弹窗
      selectedCoupon: null,
      availableCoupons: [], // 可用优惠券列表
      showCouponModal: false, // 优惠券选择弹窗
      remarks: '',
      appointmentTime: '立即预约',
      showAppointmentModal: false,
      showPaymentModal: false,
      selectedDateIndex: 0,
      selectedTimeIndex: 0,
      currentDateTime: '',
      availableDates: [],
      availableTimes: [],
      paymentPassword: '',
      orderNumber: '',
      verifyingPassword: false // 是否正在验证密码
    }
  },
  
  computed: {
    totalPrice() {
      let total = this.orderData.selectedServices.reduce((sum, service) => {
        return sum + parseInt(service.currentPrice);
      }, 0);
      
      // 如果有优惠券，计算优惠后金额
      if (this.selectedCoupon && this.selectedCoupon.coupon) {
        if (this.selectedCoupon.coupon.type === '满减券') {
          // 满减券：满足条件时减去优惠金额
          if (total >= this.selectedCoupon.coupon.triggerMoney) {
            total -= this.selectedCoupon.coupon.preferentialMoney;
          }
        } else if (this.selectedCoupon.coupon.type === '折扣券') {
          // 折扣券：按折扣比例计算
          total = total * this.selectedCoupon.coupon.discount;
        }
      }
      
      return Math.max(0, total).toFixed(2);
    }
  },
  
  onLoad(options) {
    console.log('确认订单页面接收到的数据:', options);
    
    if (options.orderData) {
      try {
        this.orderData = JSON.parse(decodeURIComponent(options.orderData));
        console.log('解析后的订单数据:', this.orderData);
      } catch (error) {
        console.error('解析订单数据失败:', error);
        uni.showToast({
          title: '数据解析失败',
          icon: 'none'
        });
      }
    }
    
    // 获取用户ID（从本地存储或登录状态获取）
    this.userId = uni.getStorageSync('userId') || 1; // 默认用户ID为1
    
    // 初始化页面数据
    this.initPageData();
  },
  

  
  methods: {
    // 初始化页面数据
    async initPageData() {
      await Promise.all([
        this.loadUserInfo(),
        this.loadDefaultVehicle(),
        this.initAppointmentTimeData()
      ]);
    },

    // 加载用户信息
    async loadUserInfo() {
      try {
        this.loadingUser = true;
        const response = await userApi.getUserById(this.userId);
        
        if (response.code === 200 && response.data) {
          this.userInfo = this.formatUserInfo(response.data);
        } else {
          // 使用默认用户信息
          this.userInfo = {
            id: this.userId,
            name: '默认用户',
            phone: '18602564789'
          };
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
        // 使用默认用户信息
        this.userInfo = {
          id: this.userId,
          name: '默认用户',
          phone: '18602564789'
        };
      } finally {
        this.loadingUser = false;
      }
    },

    // 加载用户车辆信息
    async loadDefaultVehicle() {
      // 先加载车辆列表，再加载默认车辆
      await this.loadUserCars();
      await this.loadDefaultCar();
    },

    // 加载用户车辆列表
    async loadUserCars() {
      try {
        console.log('开始获取用户车辆列表, userId:', this.userId);
        const response = await maintenanceCarApi.getUserCars(this.userId);
        console.log('车辆列表API响应:', response);
        
        if (response.code === 200 && response.data && Array.isArray(response.data)) {
          this.vehicleList = response.data.map(car => this.formatCarData(car));
          console.log('格式化后的车辆列表:', this.vehicleList);
        } else {
          console.log('获取车辆列表失败或数据为空:', response);
          this.vehicleList = [];
        }
      } catch (error) {
        console.error('获取车辆列表失败:', error);
        this.vehicleList = [];
      }
    },

    // 加载用户默认车辆
    async loadDefaultCar() {
      try {
        this.loadingVehicle = true;
        const response = await maintenanceCarApi.getUserDefaultCar(this.userId);
        
        if (response.code === 200 && response.data) {
          this.vehicleInfo = this.formatCarData(response.data);
          console.log('获取到的默认车辆:', this.vehicleInfo);
        } else {
          console.log('没有获取到默认车辆，使用列表第一个或占位符');
          // 如果没有默认车辆，使用车辆列表的第一个
          if (this.vehicleList.length > 0) {
            this.vehicleInfo = { ...this.vehicleList[0] };
            console.log('使用列表第一个车辆:', this.vehicleInfo);
          } else {
            this.vehicleInfo = {
              id: null,
              type: '请选择车辆',
              carNum: '',
              brand: '',
              model: ''
            };
            console.log('没有车辆数据，使用占位符');
          }
        }
      } catch (error) {
        console.error('获取默认车辆失败:', error);
        // 使用车辆列表的第一个或默认信息
        if (this.vehicleList.length > 0) {
          this.vehicleInfo = { ...this.vehicleList[0] };
        } else {
          this.vehicleInfo = {
            id: null,
            type: '请选择车辆',
            carNum: '',
            brand: '',
            model: ''
          };
        }
      } finally {
        this.loadingVehicle = false;
      }
    },

    // 格式化车辆数据
    formatCarData(car) {
      console.log('格式化车辆数据:', car);
      return {
        id: car.id,
        type: car.type || '未知车型',
        carNum: car.carNum || '未知车牌',
        brand: this.extractBrand(car.type),
        model: this.extractModel(car.type),
        isDefault: car.defaultCar === 1,
        avatar: car.avater || '/static/car-default.png'
      };
    },

    // 从车型中提取品牌
    extractBrand(type) {
      if (!type) return '';
      const parts = type.split(' ');
      return parts[0] || '';
    },

    // 从车型中提取型号
    extractModel(type) {
      if (!type) return '';
      const parts = type.split(' ');
      return parts.slice(1).join(' ') || '';
    },

    // 格式化用户信息
    formatUserInfo(user) {
      return {
        id: user.id,
        name: user.nickName || user.userName || user.name || '未知用户',
        phone: user.phone || user.mobile || '未设置手机号'
      };
    },

    // 初始化预约时间数据
    initAppointmentTimeData() {
      // 设置当前时间
      const now = new Date();
      this.currentDateTime = this.formatDateTime(now);
      
      // 生成可用日期（未来4天）
      this.availableDates = [];
      for (let i = 0; i < 4; i++) {
        const date = new Date();
        date.setDate(now.getDate() + i);
        
        let dateText = '';
        if (i === 0) {
          dateText = `${this.formatDate(date)}(今天)`;
        } else if (i === 1) {
          dateText = `${this.formatDate(date)}(明天)`;
        } else if (i === 2) {
          dateText = `${this.formatDate(date)}(后天)`;
        } else {
          dateText = this.formatDate(date);
        }
        
        this.availableDates.push({
          text: dateText,
          disabled: i === 3, // 最后一天禁用
          date: date
        });
      }
      
      // 生成可用时间（18:00-21:00，每小时一个时间段）
      this.availableTimes = [];
      for (let hour = 18; hour <= 21; hour++) {
        const timeText = `${hour}点`;
        const isDisabled = this.isTimeDisabled(now, hour);
        this.availableTimes.push({
          text: timeText,
          disabled: isDisabled,
          hour: hour
        });
      }
      
      // 设置默认预约时间为立即预约
      this.appointmentTime = '立即预约';
    },
    
    // 检查时间是否应该被禁用
    isTimeDisabled(now, hour) {
      const currentHour = now.getHours();
      
      // 如果是今天，且时间已经过去，则禁用
      if (hour <= currentHour) {
        return true;
      }
      
      // 21点后禁用
      if (hour >= 22) {
        return true;
      }
      
      return false;
    },
    
    // 格式化日期
    formatDate(date) {
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${month}月${day}日`;
    },
    
    // 格式化日期时间
    formatDateTime(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hour = date.getHours().toString().padStart(2, '0');
      const minute = date.getMinutes().toString().padStart(2, '0');
      return `${year}-${month}-${day} ${hour}:${minute}`;
    },
    
    // 选择预约时间
    selectAppointmentTime() {
      console.log('打开预约时间选择弹窗');
      this.showAppointmentModal = true;
    },
    
    // 关闭预约时间弹窗
    closeAppointmentModal() {
      this.showAppointmentModal = false;
    },
    
    // 选择立即预约
    selectBookNow() {
      console.log('选择立即预约');
      this.selectedDateIndex = 0;
      this.selectedTimeIndex = 0;
      
      // 更新当前时间显示为现在的时间
      const now = new Date();
      this.currentDateTime = this.formatDateTime(now);
    },
    
    // 选择日期
    selectDate(index) {
      if (this.availableDates[index].disabled) return;
      console.log('选择日期:', this.availableDates[index].text);
      this.selectedDateIndex = index;
    },
    
    // 选择时间
    selectTime(index) {
      if (this.availableTimes[index].disabled) return;
      console.log('选择时间:', this.availableTimes[index].text);
      this.selectedTimeIndex = index;
    },
    
    // 确认预约时间
    confirmAppointment() {
      const selectedDate = this.availableDates[this.selectedDateIndex];
      const selectedTime = this.availableTimes[this.selectedTimeIndex];
      
      if (this.selectedDateIndex === 0 && this.selectedTimeIndex === 0) {
        this.appointmentTime = '立即预约';
      } else {
        this.appointmentTime = `${selectedDate.text} ${selectedTime.text}`;
      }
      
      console.log('确认预约时间:', this.appointmentTime);
      this.closeAppointmentModal();
      
      uni.showToast({
        title: '预约时间已设置',
        icon: 'success'
      });
    },
    

    
    // 选择车辆
    selectVehicle() {
      console.log('选择车辆');
      if (this.vehicleList.length === 0) {
        uni.showToast({
          title: '您还没有添加车辆',
          icon: 'none'
        });
        return;
      }
      this.showVehicleModal = true;
    },

    // 关闭车辆选择弹窗
    closeVehicleModal() {
      this.showVehicleModal = false;
    },

    // 选择特定车辆
    selectSpecificVehicle(vehicle) {
      this.vehicleInfo = { ...vehicle };
      this.closeVehicleModal();
      console.log('选择了车辆:', this.vehicleInfo);
      
      uni.showToast({
        title: '车辆选择成功',
        icon: 'success'
      });
    },

    // 添加新车辆
    addNewVehicle() {
      this.closeVehicleModal();
      // 这里可以跳转到添加车辆页面
      uni.showToast({
        title: '跳转到添加车辆页面',
        icon: 'none'
      });
    },
    
    // 选择优惠券
    async selectCoupon() {
      console.log('选择优惠券，店铺ID:', this.orderData?.storeInfo?.id);
      
      // 检查是否有店铺信息
      if (!this.orderData || !this.orderData.storeInfo || !this.orderData.storeInfo.id) {
        uni.showToast({
          title: '店铺信息不完整',
          icon: 'none'
        });
        console.error('店铺信息:', this.orderData);
        return;
      }
      
      try {
        uni.showLoading({ title: '加载中...' });
        
        // 获取用户在当前店铺的可用优惠券
        console.log('正在请求优惠券，店铺ID:', this.orderData.storeInfo.id);
        console.log('当前用户信息:', this.userInfo);
        
        // 检查用户登录状态
        const token = uni.getStorageSync('token');
        console.log('用户token:', token ? '已存在' : '不存在');
        
        const response = await maintenanceCouponApi.getUserAvailableCouponsByMerchant(this.orderData.storeInfo.id);
        console.log('优惠券接口响应:', response);
        
        if (response && response.code === 200) {
          this.availableCoupons = response.data || [];
          console.log('获取到优惠券:', this.availableCoupons);
          
          if (this.availableCoupons.length === 0) {
            uni.showToast({
              title: '暂无可用优惠券',
              icon: 'none'
            });
          } else {
            this.showCouponModal = true;
          }
        } else {
          console.error('获取优惠券失败，响应:', response);
          uni.showToast({
            title: response?.msg || '获取优惠券失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取优惠券异常:', error);
        uni.showToast({
          title: '网络异常，请稍后重试',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    },

    // 选择指定优惠券
    selectSpecificCoupon(coupon) {
      this.selectedCoupon = coupon;
      this.showCouponModal = false;
      uni.showToast({
        title: '优惠券选择成功',
        icon: 'success'
      });
    },

    // 不使用优惠券
    selectNoCoupon() {
      this.selectedCoupon = null;
      this.showCouponModal = false;
      uni.showToast({
        title: '已取消优惠券',
        icon: 'none'
      });
    },

    // 关闭优惠券弹窗
    closeCouponModal() {
      this.showCouponModal = false;
    },

    // 格式化优惠券金额显示
    formatCouponAmount(coupon) {
      if (coupon.coupon.type === '满减券') {
        return `满${coupon.coupon.triggerMoney}减${coupon.coupon.preferentialMoney}`;
      } else if (coupon.coupon.type === '折扣券') {
        return `${(coupon.coupon.discount * 10).toFixed(1)}折`;
      }
      return coupon.coupon.name;
    },

    // 检查优惠券是否可用
    isCouponUsable(coupon) {
      if (coupon.coupon.type === '满减券') {
        const totalAmount = this.orderData.selectedServices.reduce((sum, service) => {
          return sum + parseInt(service.currentPrice);
        }, 0);
        return totalAmount >= coupon.coupon.triggerMoney;
      }
      return true; // 折扣券通常都可用
    },
    
    // 提交订单
    async submitOrder() {
      console.log('提交订单');
      
      // 验证必要信息
      if (!this.userInfo.id) {
        uni.showToast({
          title: '用户信息不完整',
          icon: 'none'
        });
        return;
      }
      
      if (!this.vehicleInfo.id) {
        uni.showToast({
          title: '请选择车辆',
          icon: 'none'
        });
        return;
      }
      
      if (!this.orderData.selectedServices || this.orderData.selectedServices.length === 0) {
        uni.showToast({
          title: '请选择服务项目',
          icon: 'none'
        });
        return;
      }
      
      // 数据验证通过，显示支付密码弹窗
      this.showPaymentModal = true;
    },

    // 准备订单数据
    prepareOrderData() {
      // 解析预约时间
      let appointmentDateTime = null;
      if (this.appointmentTime !== '立即预约') {
        // 这里需要将appointmentTime转换为具体的日期时间
        appointmentDateTime = new Date();
      }
      
      const orderData = {
        userId: this.userInfo.id,
        vehicleId: this.vehicleInfo.id,
        storeId: this.orderData.storeInfo.id,
        orderStatus: 1, // 1-进行中（支付成功后的状态，而不是0-待支付）
        repairMode: '到店维修',
        appointTime: appointmentDateTime,
        remark: this.remarks,
        payAmount: parseFloat(this.totalPrice),
        typeId: 2, // 汽车保养服务类型
        couponId: this.selectedCoupon ? this.selectedCoupon.id : null, // 优惠券ID
        serviceIds: this.orderData.selectedServices.map(service => service.id) // 服务ID列表
      };
      
      return orderData;
    },
    
    // 关闭支付密码弹窗
    closePaymentModal() {
      this.showPaymentModal = false;
      this.paymentPassword = '';
      this.verifyingPassword = false;
    },
    
    // 处理密码输入
    onPasswordInput(e) {
      const value = e.detail.value;
      // 限制只能输入数字
      this.paymentPassword = value.replace(/[^0-9]/g, '');
      
      // 如果输入满6位，自动验证密码
      if (this.paymentPassword.length === 6) {
        console.log('密码输入完成，开始自动验证');
        // 延迟一下再验证，给用户一点反馈时间
        setTimeout(() => {
          this.verifyPaymentPassword();
        }, 300);
      }
    },
    
    // 验证支付密码
    async verifyPaymentPassword() {
      // 防止重复验证
      if (this.verifyingPassword) {
        return;
      }
      
      try {
        this.verifyingPassword = true;
        console.log('验证支付密码:', this.paymentPassword);
        
        // 显示加载状态
        uni.showLoading({ title: '验证中...' });
        
        // 调用后端验证支付密码
        const response = await userApi.verifyPayPassword({
          payPassword: this.paymentPassword
        });
        
        console.log('支付密码验证响应:', response);
        
        if (response && response.code === 200) {
          // 验证成功，处理支付成功逻辑
          uni.hideLoading();
          this.handlePaymentSuccess();
        } else {
          // 验证失败
          uni.hideLoading();
          uni.showToast({
            title: response.msg || '支付密码错误',
            icon: 'none'
          });
          
          // 清空密码，允许重新输入
          this.paymentPassword = '';
        }
      } catch (error) {
        console.error('支付密码验证失败:', error);
        uni.hideLoading();
        uni.showToast({
          title: '网络异常，请稍后重试',
          icon: 'none'
        });
        
        // 清空密码，允许重新输入
        this.paymentPassword = '';
      } finally {
        this.verifyingPassword = false;
      }
    },
    
    // 处理支付成功
    async handlePaymentSuccess() {
      console.log('支付成功，开始创建订单');
      
      try {
        // 显示订单创建中的提示
        uni.showLoading({ title: '创建订单中...' });
        
        // 准备订单数据
        const orderData = this.prepareOrderData();
        console.log('准备提交的订单数据:', orderData);
        
        // 调用后端创建订单的API
        const response = await maintenanceOrderApi.createOrder(orderData);
        
        console.log('[ORDER-CREATE] 后端返回响应:', response);
        uni.hideLoading();
        
        if (response.code === 200) {
          // 订单创建成功，获取后端返回的订单信息
          console.log('[ORDER-CREATE] 订单创建成功，后端返回数据:', response.data);
          
          // 从后端返回的明确数据结构中获取订单信息
          if (response.data && response.data.orderNumber) {
            this.orderNumber = response.data.orderNumber;
            console.log('[ORDER-CREATE] 使用后端返回的订单号:', this.orderNumber);
          } else {
            console.error('[ORDER-CREATE] 后端未返回有效的订单号');
            throw new Error('订单创建成功但未获取到订单号');
          }
          
          // 关闭支付密码弹窗
          this.closePaymentModal();
          
          // 显示支付成功提示
          uni.showToast({
            title: '支付成功',
            icon: 'success'
          });
          
          // 延迟跳转到支付成功页面或订单详情页面
          setTimeout(() => {
            this.goToOrderPayment();
          }, 1500);
        } else {
          // 订单创建失败
          uni.showToast({
            title: response.msg || '订单创建失败，请重试',
            icon: 'none'
          });
          
          // 清空密码，允许重新支付
          this.paymentPassword = '';
        }
      } catch (error) {
        console.error('订单创建失败:', error);
        uni.hideLoading();
        
        uni.showToast({
          title: '网络异常，订单创建失败',
          icon: 'none'
        });
        
        // 清空密码，允许重新支付
        this.paymentPassword = '';
      }
    },
    
    // 跳转到订单支付页面
    goToOrderPayment() {
      this.closePaymentModal();
      
      // 准备完整的订单数据
      const completeOrderData = {
        // 基本订单信息
        amount: this.totalPrice,
        orderNumber: this.orderNumber,
        
        // 店铺信息
        storeInfo: {
          name: this.orderData.storeInfo.name || '伟业汽车维修厂(人民路店)',
          address: this.orderData.storeInfo.address || '山阳区人民中路32号'
        },
        
        // 服务项目
        services: this.orderData.selectedServices.map(service => ({
          name: service.name,
          price: service.currentPrice
        })),
        
        // 价格明细
        pricing: {
          originalPrice: this.orderData.selectedServices.reduce((sum, service) => sum + parseInt(service.currentPrice), 0).toString(),
          discount: this.selectedCoupon && this.selectedCoupon.coupon.type === '满减券' ? this.selectedCoupon.coupon.preferentialMoney.toString() : '0',
          coupon: this.selectedCoupon && this.selectedCoupon.coupon.type === '折扣券' ? ((1 - this.selectedCoupon.coupon.discount) * this.orderData.selectedServices.reduce((sum, service) => sum + parseInt(service.currentPrice), 0)).toString() : '0',
          finalAmount: this.totalPrice
        },
        
        // 订单信息
        orderInfo: {
          orderTime: this.formatDateTime(new Date()),
          appointmentTime: this.appointmentTime || '立即预约',
          vehicle: this.vehicleInfo.id ? `${this.vehicleInfo.type}/${this.vehicleInfo.carNum}` : '未选择车辆',
          notes: this.remarks || ''
        },
        
        // 用户信息
        userInfo: {
          name: this.userInfo.name,
          phone: this.userInfo.phone
        },
        
        // 优惠券信息
        couponInfo: this.selectedCoupon ? {
          id: this.selectedCoupon.id,
          name: this.selectedCoupon.coupon.name,
          type: this.selectedCoupon.coupon.type,
          discount: this.selectedCoupon.coupon.discount || 0,
          preferentialMoney: this.selectedCoupon.coupon.preferentialMoney || 0
        } : null
      };
      
      uni.navigateTo({
        url: `/pages/orderPayment/orderPayment?orderData=${encodeURIComponent(JSON.stringify(completeOrderData))}`
      });
    }
  }
}
</script>

<style scoped>
.confirm-order-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

/* 进度指示器 */
.progress-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.progress-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.progress-step {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.step-circle {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  background-color: #ddd;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.progress-step.completed .step-circle {
  background-color: #007AFF;
}

.progress-step.current .step-circle {
  background-color: #ff6b35;
}

.step-text {
  font-size: 24rpx;
  color: #666;
}

.progress-line {
  flex: 1;
  height: 2rpx;
  background-color: #ddd;
  margin: 0 20rpx;
  margin-bottom: 30rpx;
}

/* 信息区域 */
.info-section {
  background-color: #fff;
  margin-bottom: 20rpx;
}

.info-item {
  display: flex;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.info-item.clickable {
  cursor: pointer;
}

.info-icon {
  width: 48rpx;
  height: 48rpx;
  margin-right: 20rpx;
  flex-shrink: 0;
}

.info-content {
  flex: 1;
}

.info-title {
  font-size: 28rpx;
  color: #333;
  display: block;
  margin-bottom: 5rpx;
}

.vehicle-placeholder {
  color: #999;
  font-weight: normal;
}

.info-desc {
  font-size: 24rpx;
  color: #666;
}

.arrow-icon {
  width: 32rpx;
  height: 32rpx;
  margin-left: 10rpx;
}

/* 服务产品 */
.services-section {
  background-color: #fff;
  margin-bottom: 20rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.service-count {
  font-size: 24rpx;
  color: #007AFF;
}

.service-list {
  padding: 0 30rpx;
}

.service-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.service-item:last-child {
  border-bottom: none;
}

.service-name {
  font-size: 28rpx;
  color: #333;
  flex: 1;
}

.service-price {
  font-size: 28rpx;
  color: #ff6b35;
  font-weight: bold;
}

/* 备注信息 */
.remarks-section {
  background-color: #fff;
  margin-bottom: 20rpx;
  padding: 30rpx;
}

.remarks-label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.remarks-input {
  width: 100%;
  height: 200rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: 28rpx;
  color: #333;
  background-color: #f9f9f9;
}

/* 底部操作栏 */
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  border-top: 1rpx solid #e5e5e5;
  padding: 20rpx 30rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.left-section {
  display: flex;
  align-items: center;
}

.customer-service {
  display: flex;
  align-items: center;
}

.service-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 10rpx;
}

.service-text {
  font-size: 24rpx;
  color: #666;
}

.right-section {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.total-price {
  display: flex;
  align-items: center;
}

.total-label {
  font-size: 28rpx;
  color: #333;
  margin-right: 10rpx;
}

.total-value {
  font-size: 32rpx;
  color: #ff6b35;
  font-weight: bold;
}

.submit-btn {
  background-color: #ff6b35;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  padding: 20rpx 40rpx;
  font-size: 28rpx;
  font-weight: bold;
}

.submit-btn:active {
  background-color: #e55a2b;
}

/* 预约时间选择弹窗 */
.appointment-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.appointment-modal {
  width: 80%;
  max-width: 600rpx;
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.15);
}

.modal-header {
  padding: 40rpx 30rpx 20rpx;
  text-align: center;
  border-bottom: 1rpx solid #f0f0f0;
}

.modal-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}

.modal-subtitle {
  font-size: 24rpx;
  color: #666;
}

.modal-content {
  padding: 30rpx;
}

.book-now-option {
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  margin-bottom: 30rpx;
}

.book-now-text {
  font-size: 32rpx;
  color: #007AFF;
  font-weight: bold;
}

.time-selection {
  display: flex;
  gap: 40rpx;
}

.date-column, .time-column {
  flex: 1;
}

.date-item, .time-item {
  padding: 20rpx 0;
  text-align: center;
  border-radius: 8rpx;
  margin-bottom: 10rpx;
  cursor: pointer;
  transition: all 0.2s ease;
}

.date-item:hover, .time-item:hover {
  background-color: #f5f5f5;
}

.date-item.selected, .time-item.selected {
  background-color: #007AFF;
}

.date-item.disabled, .time-item.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.date-text, .time-text {
  font-size: 28rpx;
  color: #333;
}

.date-item.selected .date-text, .time-item.selected .time-text {
  color: #fff;
}

.date-item.disabled .date-text, .time-item.disabled .time-text {
  color: #999;
}

.modal-footer {
  display: flex;
  border-top: 1rpx solid #f0f0f0;
}

.cancel-btn, .confirm-btn {
  flex: 1;
  height: 100rpx;
  border: none;
  font-size: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #666;
}

.confirm-btn {
  background-color: #007AFF;
  color: #fff;
}

.cancel-btn:active {
  background-color: #e5e5e5;
}

.confirm-btn:active {
  background-color: #0056cc;
}

/* 车辆选择弹窗 */
.vehicle-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.vehicle-modal {
  width: 85%;
  max-width: 650rpx;
  max-height: 80vh;
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
}

.vehicle-modal .modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.vehicle-modal .modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.vehicle-modal .close-btn {
  font-size: 40rpx;
  color: #999;
  cursor: pointer;
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.vehicle-modal .modal-content {
  flex: 1;
  padding: 20rpx 30rpx;
  overflow-y: auto;
  max-height: 400rpx;
}

.vehicle-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 25rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.vehicle-item:last-child {
  border-bottom: none;
}

.vehicle-item:hover {
  background-color: #f9f9f9;
}

.vehicle-item.selected {
  background-color: #f0f8ff;
}

.vehicle-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.vehicle-type {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
}

.vehicle-number {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 5rpx;
}

.default-tag {
  display: inline-block;
  background-color: #007AFF;
  color: #fff;
  font-size: 20rpx;
  padding: 4rpx 12rpx;
  border-radius: 10rpx;
  align-self: flex-start;
}

.vehicle-check {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  background-color: #007AFF;
  display: flex;
  align-items: center;
  justify-content: center;
}

.check-icon {
  color: #fff;
  font-size: 24rpx;
  font-weight: bold;
}

.no-vehicle {
  text-align: center;
  padding: 60rpx 0;
  color: #999;
  font-size: 28rpx;
}

.vehicle-modal .modal-footer {
  padding: 20rpx 30rpx 30rpx;
  border-top: 1rpx solid #f0f0f0;
}

.add-vehicle-btn {
  width: 100%;
  height: 80rpx;
  background-color: #007AFF;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  font-size: 28rpx;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
}

.add-vehicle-btn:active {
  background-color: #0056cc;
}

/* 优惠券选择弹窗 */
.coupon-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.coupon-modal {
  width: 85%;
  max-width: 650rpx;
  max-height: 80vh;
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
}

.coupon-modal .modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.coupon-modal .modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.coupon-modal .close-btn {
  font-size: 40rpx;
  color: #999;
  cursor: pointer;
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.coupon-modal .modal-content {
  flex: 1;
  overflow-y: auto;
  padding: 0 30rpx;
  max-height: 60vh;
}

.coupon-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.2s;
}

.coupon-item:last-child {
  border-bottom: none;
}

.coupon-item.selected {
  background-color: #f0f8ff;
}

.coupon-item.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.coupon-item.no-coupon-item {
  background-color: #f8f8f8;
  border-radius: 8rpx;
  margin-bottom: 20rpx;
  padding: 30rpx 20rpx;
}

.coupon-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.coupon-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
}

.coupon-desc {
  font-size: 26rpx;
  color: #ff6b35;
  font-weight: bold;
  margin-bottom: 8rpx;
}

.coupon-expire {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 4rpx;
}

.coupon-condition {
  font-size: 24rpx;
  color: #ff4757;
}

.coupon-check {
  width: 40rpx;
  height: 40rpx;
  background-color: #007AFF;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 20rpx;
}

.coupon-check .check-icon {
  color: #fff;
  font-size: 24rpx;
  font-weight: bold;
}

.no-coupon {
  text-align: center;
  padding: 60rpx 0;
  color: #999;
  font-size: 28rpx;
}

/* 支付密码弹窗 */
.payment-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.payment-modal {
  width: 85%;
  max-width: 650rpx;
  background-color: #fff;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.15);
  padding: 30rpx;
}

.payment-header {
  position: relative;
  text-align: center;
  margin-bottom: 50rpx;
}

.close-btn {
  position: absolute;
  top: 0;
  right: 0;
  font-size: 36rpx;
  color: #999;
  cursor: pointer;
  width: 50rpx;
  height: 50rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.payment-title {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
}

.payment-amount {
  text-align: center;
  margin-bottom: 60rpx;
  display: flex;
  align-items: baseline;
  justify-content: center;
  gap: 5rpx;
}

.amount-symbol {
  font-size: 36rpx;
  color: #333;
  font-weight: normal;
}

.amount-number {
  font-size: 72rpx;
  color: #333;
  font-weight: bold;
}

.payment-method {
  margin-bottom: 30rpx;
}

.payment-labels {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.method-label {
  font-size: 28rpx;
  color: #333;
}

.balance-text {
  font-size: 28rpx;
  color: #007AFF;
  cursor: pointer;
}

.password-input-container {
  position: relative;
}

.hidden-input {
  position: absolute;
  opacity: 0;
  pointer-events: none;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
}

.password-boxes {
  display: flex;
  justify-content: center;
  gap: 0;
}

.password-box {
  width: 80rpx;
  height: 80rpx;
  border: 2rpx solid #ddd;
  border-right: none;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  transition: all 0.2s ease;
}

.password-box:first-child {
  border-top-left-radius: 8rpx;
  border-bottom-left-radius: 8rpx;
}

.password-box:last-child {
  border-top-right-radius: 8rpx;
  border-bottom-right-radius: 8rpx;
  border-right: 2rpx solid #ddd;
}

.password-box.filled {
  border-color: #007AFF;
  background-color: #f0f8ff;
}

.password-box.filled + .password-box {
  border-left-color: #007AFF;
}

.box-text {
  font-size: 36rpx;
  color: #333;
  font-weight: bold;
}
</style>
